<template>
    <el-form :model="baseInfoForm" label-width="100px" size="small" class="form_box" :label-position="'top'">
        <el-row :gutter="40">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24"><h4>商品类型</h4></el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item>
                    <el-radio-group v-model="baseInfoForm.storeType">
                        <el-radio label="0" border>实物商品（需要物流）</el-radio>
                        <el-radio label="1" border>虚拟商品（无需物流）</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="40">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24"><h4>基础信息</h4></el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="商品名称" :required="true">
                    <el-input size="small" placeholder="请输入商品名称" v-model.trim="baseInfoForm.storeTitle" clearable maxlength="200" show-word-limit @input="watchInput"></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="商品分类" :required="true">
                    <el-cascader size="small" placeholder="请选择商品分类" v-model="baseInfoForm.storeClass" filterable clearable ref="cascaderRef" :options="storeClassList" @change="handleStoreClassChange" :props="defaultProps" class="full-width" :disabled="isEdit"></el-cascader>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="商品品牌" :required="true">
                    <el-select size="small" placeholder="请选择商品品牌" v-model="baseInfoForm.storeBrand" filterable clearable class="full-width" :value-key="'label'" :disabled="isEdit">
                        <el-option v-for="item in storeBrandList" :key="item.value" :label="item.label" :value="item" :disabled="item.disabled"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="商品供应商" :required="true">
                    <el-select size="small" class="full-width" v-model="baseInfoForm.storeSupply" filterable clearable placeholder="请选择商品供应商" :value-key="'label'" :disabled="isEdit">
                        <el-option v-for="item in storeSupplyList" :key="item.value" :label="item.label" :value="item" :disabled="item.disabled"></el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="商品编码（SPU）" :required="true">
                    <el-input size="small" v-model.trim="baseInfoForm.storeSPUNo" placeholder="自动生成商品编码" :disabled="true"></el-input>
                </el-form-item>
            </el-col>
            <!-- <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="商品税码">
                    <el-input size="small" v-model.trim="baseInfoForm.storeTaxNo" placeholder="请输入商品税码" maxlength="30" show-word-limit></el-input>
                </el-form-item>
            </el-col> -->            
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="生产年份">
                    <el-date-picker class="datePick" size="small" v-model.trim="baseInfoForm.storeCreateTime" :value-format="'yyyy'" placeholder="请选择生产年份" type="year"></el-date-picker>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                <el-form-item label="供应商货号">
                    <el-input size="small" type="textarea" v-model.trim="baseInfoForm.storeSupplyNo" placeholder="请输入供应商货号" :rows="4" maxlength="200" show-word-limit></el-input>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-show="isShowCustom">
                <el-form-item label="交货周期">
                    <div>
                        <span class="margin_right_6">预计</span>
                        <el-input-number style="width: 49px" :controls="false" v-model.trim="baseInfoForm.storeStartTime" placeholder="请输入" :precision="0" :min="0" @keydown.native="inputNoneNumberUnpass"></el-input-number>
                        <span class="margin_left_6 margin_right_6"> ~ </span>
                        <el-input-number style="width: 49px" :controls="false" v-model.trim="baseInfoForm.storeEndTime" placeholder="请输入" :precision="0" :min="0" @keydown.native="inputNoneNumberUnpass"></el-input-number>
                        <span class="margin_left_6">个工作日交货</span>
                    </div>
                </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="商品介绍">
                    <el-input size="small" type="textarea" v-model="baseInfoForm.storeSubtitle" placeholder="请输入商品介绍" maxlength="200" show-word-limit></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="40">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <h4>图片信息 <span class="font-size--sm text-gray font-weight--sm"><i class="el-icon-warning"></i> 图片格式为jpg或png，最少上传2张，最多上传6张，首张默认为封面图</span></h4>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="商品图片" :required="true">
                    <store-image :initFiles="storeImageList" @update="imgSuccessOption"></store-image>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="40">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <h4>视频信息 <span class="font-size--sm text-gray font-weight--sm"><i class="el-icon-warning"></i> 视频格式为{{fileFormat.join(',')}}，最大不可以超过50M。</span></h4>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="商品视频">
                    <app-uploader title="商品视频" :limit="1" :initFiles="storeVideoList" :accept="'video/*'" :file-format="fileFormat" :file-size="50" @change="handleVideoOption($event)"></app-uploader>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row :gutter="40">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <h4>商品详情 <span class="font-size--sm text-gray font-weight--sm"><i class="el-icon-warning"></i>提示内容：单次图片上传尽量以10个位单位进行上传，最多支持20张（速度较慢），上传顺序为图片所在文件夹中的顺序</span></h4>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item class="full-width">
                    <AppEditor v-model="storeDetail" :config="{zIndex: 99}" ref="myEditorRef"></AppEditor>
                    <!-- <tinymce :key="tinymceFlag" :value="storeDetail" @input="getEditorContent"></tinymce> -->
                </el-form-item>
            </el-col>
        </el-row>
    </el-form>
</template>

<script>
import StoreImage from './storeImage.vue';
import AppEditor from '@/components/AppEditor/index';
import Tinymce from '@/components/Tinymce';
import AppUploader from '@/components/AppUploader/index';
import { GetStoreBrandAllListByParams, GetStoreSupplyListAll, GetStoreClassList, GetStoreClassDetail, CheckSPUCodeIsContain, GetRandomString } from '@/views/store-management/services/index';

export default {
    components: {
        AppEditor,
        StoreImage,
        AppUploader
    },
    props: ['storeId', 'storeAttrListAll', 'detail', 'newAttr'],
    data() {
        return {
            defaultProps: {
                children: 'goodsCategoryModelList',
                label: 'title',
                value: 'id'
            },
            baseInfoForm: {
                storeType: '0',
                storeTitle: '', // 商品名称
                storeClass: [], // 商品分类
                storeBrand: null, // 商品品牌
                storeSupply: null, // 商品供应商
                storeSPUNo: '', // 商品编码
                storeTaxNo: '', // 商品税号
                storeCreateTime: '',//生产年份
                storeStartTime: 0, // 交货时间
                storeEndTime: 0, // 交货时间
                storeSubtitle: '', // 商品介绍
                storeSupplyNo: '' // 商品供应商货号
            },
            storeImageList: [], // 商品图片列表
            storeVideoList: [],
            storeLogoImg: [], // 商品封面
            storeDetail: null, // 商品详情

            isStoreAttrChange: false,
            oldStoreAttr: [],

            // 基本数据支持
            storeClassList: [],
            storeClassListFloat: [], // 商品分类扁平化
            storeBrandList: [],
            storeSupplyList: [],

            propertiesList: [],
            randomString: '',
            // checkPassStoreNo: null,
            // tinymceFlag: 1,
            isFinishSetData: true,
            isOldData: false,
            isShowCustom: false,
            hasGetNewRandom: false,
            fileFormat: ['avi', 'mpeg', 'mov', 'flv', 'mp4', 'rmvb'],
            isEdit: false
        }
    },
    watch: {
        'baseInfoForm.storeClass': {
            immediate: true,
            handler: function(newValue) {
                this.checkIsRanderCode();
            }
        },
        'baseInfoForm.storeSupply': {
            immediate: true,
            handler: function(newValue, oldValue) {
                this.randomString = '';
                this.checkIsRanderCode();
            }
        },
        'baseInfoForm.storeBrand': {
            immediate: true,
            handler: function(newValue) {
                this.checkIsRanderCode();
            }
        },
        'detail': {
            immediate: true,
            handler: function(newValue) {
                if (!newValue) return;
                this.isFinishSetData = false;
                this.setFormData(newValue);
            }
        }
    },
    // activated() {
    //     this.tinymceFlag ++;
    // },
    activated() {
        this.getStoreClassList();
        this.getStoreBrandList();
        this.getStoreSupplyList();
    },
    methods: {
        watchInput(event) {
            this.baseInfoForm.storeTitle = this.inputReplaceSpecialChar(event);
        },
        // getEditorContent(event) {
        //     this.storeDetail = event;
        // },
        functionIsGetRandom(id) {
            return new Promise((resolve, reject) => {
                if (this.hasGetNewRandom && this.randomString) {
                    resolve(this.randomString);
                    return;
                }
                GetRandomString({id})
                .then(data => {
                    if (data.code == 200 && data.data) {
                        this.hasGetNewRandom = true;
                        resolve(data.data);
                    } else {
                        reject(data.msg);
                    }
                })
                .catch(error => {
                    reject(error);
                })
            })
        },
        checkIsRanderCode() {
            if (!this.isFinishSetData) return;
            // 检查是否填写完整
            if (!this.baseInfoForm.storeClass || !this.baseInfoForm.storeClass.length) {
                this.baseInfoForm.storeSPUNo = '';
                return;
            };
            if (!this.baseInfoForm.storeSupply || !this.baseInfoForm.storeSupply.value) {
                this.baseInfoForm.storeSPUNo = '';
                return;
            };
            if (!this.baseInfoForm.storeBrand || !this.baseInfoForm.storeBrand.value) {
                this.baseInfoForm.storeSPUNo = '';
                return;
            };
            if (this.randomString) {
                this.autoRenderStoreCode();
                return;
            }
            // 获取随机字符串
            this.functionIsGetRandom(this.baseInfoForm.storeSupply.value)
                .then(data => {
                    this.randomString = data;
                    this.autoRenderStoreCode();
                })
                .catch(error => {
                    this.$alert('SPU编码生成失败，将会为您重新生成!', '提示', {
                        confirmButtonText: '确定',
                        showClose: false,
                        closeOnClickModal: false,
                        closeOnPressEscape: false,
                        callback: action => {
                            this.checkIsRanderCode();
                        }
                    });
                })
        },
        // 自动计算编码
        autoRenderStoreCode() {
            this.checkClassIsOver()
            .then(over => {
                const storeClassList = this.baseInfoForm.storeClass.map(classId => {
                    const finder = this.storeClassListFloat.find(item => item.id == classId);
                    return finder ? finder : '';
                })
                const storeClassNameList = storeClassList.filter(item => item && item.name).map(item => item.name);
                if (storeClassNameList.join('').indexOf('定制') >= 0) {
                    this.isShowCustom = true;
                } else {
                    this.isShowCustom = false;
                }
                const storeClassCodeList = storeClassList.filter(item => item && item.code).map(item => item.code);
                const storeClassCode = this.autoComplateString(storeClassCodeList.join(''), 5);
                // 供应商编号
                let supplyCode, brandCode;
                if (this.baseInfoForm.storeSupply.code) {
                    supplyCode = this.autoComplateString(this.baseInfoForm.storeSupply.code, 10);
                } else {
                    let finder = this.storeSupplyList.find(item => item.value == this.baseInfoForm.storeSupply.value);
                    finder = finder ? finder.code : '';
                    supplyCode = this.autoComplateString(finder, 10);
                }
                // 品牌编码
                if (this.baseInfoForm.storeBrand.code) {
                    brandCode = this.autoComplateString(this.baseInfoForm.storeBrand.code, 4);
                } else {
                    let finder = this.storeBrandList.find(item => item.value == this.baseInfoForm.storeBrand.value);
                    finder = finder ? finder.code : '';
                    brandCode = this.autoComplateString(finder, 4);
                }

                this.baseInfoForm.storeSPUNo = storeClassCode + supplyCode + brandCode + this.randomString;

                // 满足条件后再检查
                // if (!storeClassCodeList.length || !storeSupplyCode) return;
                // if (this.checkPassStoreNo == this.baseInfoForm.storeSPUNo) return;
                
                // 调接口检测SPU是否重复
                // CheckSPUCodeIsContain({ goodsNo: this.baseInfoForm.storeSPUNo, id: this.storeId })
                // .then(res => {
                //     if (res.code == 200) {
                //         if (res.data) {
                //             this.$alert('检测到SPU编码重复，将会为您重新生成!', '提示', {
                //                 confirmButtonText: '确定',
                //                 callback: action => {
                //                     this.checkIsRanderCode();
                //                 }
                //             });
                //         } else {
                //             this.checkPassStoreNo = this.baseInfoForm.storeSPUNo;
                //         }
                //     }
                // })
            })
        },
        // 检查商品分类是否加载完成
        checkClassIsOver() {
            return new Promise(resolve => {
                const timer = setInterval(() => {
                    if (this.storeClassListFloat && this.storeClassListFloat.length) {
                        clearInterval(timer);
                        resolve(true);
                    }
                }, 100)
            })
        },
        // 新增商品封面图图片
        storeLogoImgSuccessOption(event) {
            this.storeLogoImg = event.map(item => item.fileUrl);
        },
        handleVideoOption(value) {
            if (value && value.length) {
                this.storeVideoList = [value[0].fileUrl];
            } else {
                this.storeVideoList = [];
            }
        },
        // 商品图片上传回调
        imgSuccessOption(event) {
            this.storeImageList = event.map(item => item.fileUrl);
        },
        handleStoreAttrChange(e) {
            if (!this.storeId) {
                this.oldStoreAttr = JSON.parse(JSON.stringify(e));
                return;
            }

            if (e != this.oldStoreAttr) {
                this.isStoreAttrChange = true;
                this.oldStoreAttr = JSON.parse(JSON.stringify(e));
            }
        },
        // 商品类型数据更改
        handleStoreClassChange(value) {
            // if (!value || !value.length) {
            //     this.baseInfoForm.storeAttr = []; // 同时清空选中的商品属性列表
            //     this.propertiesList = this.storeAttrListAll.map(item => item);
            // } else {
            //     this.getPropertiesList(value[value.length-1]);
            // }
            if (!value || !value.length) {
                this.baseInfoForm.storeAttr = []; // 同时清空选中的商品属性列表
                this.propertiesList = [];
                this.$emit('update:newAttr', []);
            } else {
                this.getPropertiesList(value[value.length - 1])
                    .then(list => {
                        if (list && list.length) {
                            this.propertiesList = list;
                            this.$emit('update:newAttr', JSON.parse(JSON.stringify(list)));
                        } else {
                            this.getPropertiesList(value[value.length - 2])
                            .then(plist => {
                                if (plist && plist.length) {
                                    this.propertiesList = plist;
                                    this.$emit('update:newAttr', JSON.parse(JSON.stringify(plist)));
                                } else {
                                    this.$alert('该分类下没有绑定的属性，请绑定属性后再选择该分类!', '提示', {
                                        confirmButtonText: '确定',
                                        showClose: false,
                                        closeOnClickModal: false,
                                        closeOnPressEscape: false,
                                        callback: action => {
                                            // this.$router.back();
                                            this.baseInfoForm.storeClass = [];
                                            this.isShowCustom = false;
                                            if (this.$route.query.nextStep && this.$route.query.nextStep > 1) {
                                                this.$parent.$parent.stepActive = 1;
                                            }
                                        }
                                    });
                                }
                            })
                        }
                    })
            }
        },
        // 获取当前的商品属性值
        getPropertiesList(id) {
            return new Promise(resolve => {
                GetStoreClassDetail({ id: id })
                .then(res => {
                    if (res.code == 200) {
                        resolve(res.data.categoryPropertyList);
                    } else {
                        resolve(null)
                    }
                })
                .catch(error => {
                    resolve(null)
                })
            })
            GetStoreClassDetail({id: id})
            .then(res => {
                if (res.code == 200) {
                    // 没有绑定属性可以选择全部的属性
                    if (res.data.categoryPropertyList && res.data.categoryPropertyList.length) {
                        // 补充通过接口获取的属性没有编码的问题
                        this.propertiesList = res.data.categoryPropertyList.map(item => this.storeAttrListAll.find(childItem => childItem.propertyId == item.propertyId));
                    } else {
                        this.propertiesList = this.storeAttrListAll.map(item => item);
                    }
                }
            })
        },
        // 获取商品分类
        getStoreClassList() {
            GetStoreClassList()
            .then(data => {
                this.storeClassList = data.data;
                
                this.floatStoreClassData(data.data);
            })
        },
        floatStoreClassData(data) {
            // 扁平化数组，方便后面计算
            const newArray = [];
            const floatArray = function(list) {
                list.forEach(item => {
                    if (item.goodsCategoryModelList && item.goodsCategoryModelList.length) {
                        floatArray(item.goodsCategoryModelList);
                    }
                    item.goodsCategoryModelList = null;
                    newArray.push({
                        id: item.id,
                        name: item.title,
                        code: item.categoryNo
                    });
                })
            }
            floatArray(JSON.parse(JSON.stringify(data)));
            this.storeClassListFloat = newArray;
        },
        // 获取商品品牌
        getStoreBrandList() {
            GetStoreBrandAllListByParams({})
            .then(data => {
                this.storeBrandList = data.data.map(item => {
                    return {
                        value: item.id,
                        label: item.name,
                        code: item.brandNo,
                        disabled: item.status == 0
                    };
                })
            })
        },
        // 实时搜索供应商
        getStoreSupplyList(key) {
            GetStoreSupplyListAll({
                name: key,
                auditStatus: 2
            })
            .then(data => {
                this.storeSupplyList = data.data.map(item => {
                    return {
                        value: item.id,
                        label: item.name,
                        code: item.suppStandard,
                        disabled: item.status == 0
                    };
                });
            })
        },
        setFormData(value) {
            if(this.storeId) {
                this.isEdit = true
            }else {
                this.isEdit = false
            }
            const loader = this.$loading({
                lock: true,
                fullscreen: true
            });
            this.baseInfoForm.storeType = value.isEntity.toString();
            this.baseInfoForm.storeTitle = value.title;
            //获取当前商品属性值
            this.baseInfoForm.storeClass = [value.firstCategoryId, value.secondCategoryId, value.thirdCategoryId].filter(item => item);
            this.handleStoreClassChange(this.baseInfoForm.storeClass);
            this.baseInfoForm.storeBrand = value.brandId ? {
                value: value.brandId,
                label: value.brandName
            } : null;

            this.baseInfoForm.storeSupply = value.supplierId ? {
                value: value.supplierId,
                label: value.supplierName
            } : null;
            // this.checkPassStoreNo = this.baseInfoForm.storeSPUNo;
            // 赋值随机字符串
            // this.randomString = this.baseInfoForm.storeSPUNo.substr(this.baseInfoForm.storeSPUNo.length - 7, this.baseInfoForm.storeSPUNo.length);
            if (value.updateTime && !moment('2021-04-30 11:00:00').isBefore(value.updateTime)) {
                this.isOldData = true;
                this.functionIsGetRandom(value.supplierId)
                .then(data => {
                    this.randomString = data;
                    this.autoRenderStoreCode();
                })
            } else {
                this.isOldData = false;
                this.randomString = this.baseInfoForm.storeSPUNo.substr(this.baseInfoForm.storeSPUNo.length - 6, this.baseInfoForm.storeSPUNo.length);

                this.baseInfoForm.storeSPUNo = value.goodsNo;
            }
            this.baseInfoForm.storeTaxNo = value.taxNumber;
            this.baseInfoForm.storeSupplyNo = value.articleNumber;
            this.baseInfoForm.storeCreateTime = value.productionTime;
            if (value.leadTime) {
                this.baseInfoForm.storeStartTime = value.leadTime.split(',')[0];
                this.baseInfoForm.storeEndTime = value.leadTime.split(',')[1];
                this.isShowCustom = true;
            }
            this.baseInfoForm.storeSubtitle = value.subtitle;
            // 附件信息
            this.storeImageList = value.goodsFileList.filter(file => file.fileType == 1).map(file => file.fileUrl).reverse();
            this.storeImageList.unshift(value.surfaceImg);
            this.storeVideoList = value.goodsFileList.filter(file => file.fileType == 2).map(file => file.fileUrl).reverse();
            // 富文本详情图片
            this.storeDetail = value.introduction;

            this
            .watchInitData()
            .then(data => {
                loader.close();
                this.isFinishSetData = true;
                if (!this.baseInfoForm.storeSPUNo) {
                    this.checkIsRanderCode();
                }
            })
        },
        watchInitData() {
            return new Promise(resolve => {
                const timer = setInterval(() => {
                    if (this.storeSupplyList && this.storeSupplyList.length) {
                        clearInterval(timer);
                        resolve(true);
                    }
                }, 100)
           })
        }
    }
}
</script>

<style lang="scss" scoped>
.form_box {
    max-width: 1064px;
    // padding: 0 100px;
    box-sizing: content-box;
}
.datePick {
    width: 100%;
}
::v-deep .el-input-number .el-input__inner {
    text-align: left;
}
::v-deep .el-input--suffix .el-input__inner {
    padding-right: 80px;
}
</style>
